<script lang="ts" setup name="XtxCity">
import { ref, watchEffect } from 'vue';
import axios from 'axios'
import { onClickOutside } from '@vueuse/core'
import { CityItem,CityResult } from '.';
const cityList=ref(<CityItem[]>[])
const chaceList=ref(<CityItem[]>[])
const active=ref(false)
const target=ref(null)
const cityResult = ref<CityResult>({} as CityResult)
defineProps<{
  address?:string
}>()
const emit=defineEmits<{
 (e:'changeCity',city:CityResult):void
}>()
async function getCityList(){
    const res=await axios.get<CityItem[]>('https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json')
    cityList.value=res.data
    chaceList.value=res.data
}
getCityList()
//此方法,可以检测鼠标点击的区域,在盒子以外时把值设为false
onClickOutside(target,()=>{
 active.value=false
})

const selectCity=(city:CityItem)=>{
  if(city.level===0){
  cityResult.value.provinceCode=city.code
  cityResult.value.provinceName=city.name
  }
   if(city.level===1){
  cityResult.value.cityName=city.name
   cityResult.value.cityCode=city.code
  }
   if(city.level===2){
  cityResult.value.countyCode=city.code
   cityResult.value.countyName=city.name
   emit('changeCity',cityResult.value)
  }
  if(!city.areaList)return active.value=false
     cityList.value=city.areaList

watchEffect(()=>{
 if(!active.value)cityList.value=chaceList.value
})
}


</script>
<template>
  <div ref="target" class="xtx-city">
    <div @click="active=!active" :class="{active}" class="select">
      <span v-if="address" class="placeholder">{{address}}</span>
        <span v-else class="placeholder">请选择配送地址</span>
      <span class="value"></span>
      <i class="iconfont icon-angle-down"></i>
    </div>
    <div v-show="active" class="option">
      <span @click="selectCity(item)" class="ellipsis" v-for="item in cityList" :key="item.name">{{item.name}}</span>
    </div>
  </div> 
</template>

<style scoped lang="less">
.xtx-city {
  display: inline-block;
  position: relative;
  z-index: 400;
  .select {
    border: 1px solid #e4e4e4;
    height: 30px;
    padding: 0 5px;
    line-height: 28px;
    cursor: pointer;
    &.active {
      background: #fff;
    }
    .placeholder {
      color: #999;
    }
    .value {
      color: #666;
      font-size: 12px;
    }
    i {
      font-size: 12px;
      margin-left: 5px;
    }
  }
  .option {
    width: 542px;
    border: 1px solid #e4e4e4;
    position: absolute;
    left: 0;
    top: 29px;
    background: #fff;
    min-height: 30px;
    line-height: 30px;
    display: flex;
    flex-wrap: wrap;
    padding: 10px;
    > span {
      width: 130px;
      text-align: center;
      cursor: pointer;
      border-radius: 4px;
      padding: 0 3px;
      &:hover {
        background: #f5f5f5;
      }
    }
  }
}
</style>